package guiautorization;
import autorization.RegistrationFailed;
import gfdclient.ConnectWindow;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.net.UnknownHostException;
import javax.swing.*;
import gfdclient.InnerLogic;
import java.awt.event.ActionListener;
import userservercontroller.IAutorizationClient;

/**
 *
 * @author Volk, Ustinov
 */
public class RegistrationWindow extends JDialog {

    //----Class constant------------
    private final int MIN_LEN_PASSWORD = 6;
    //----Inner variables-----------
    private boolean isResult = false;
    private String login = null;
    private String password = null;
    private boolean IsAnotherComputer = false;
    private boolean IsSavePassword = false;
    private ConnectWindow wnd = new ConnectWindow(this);;
    private boolean isError = false;
    InnerLogic logic;
    //------------------------------

    /** Creates new form NewJFrame */
    public RegistrationWindow(JFrame owner, InnerLogic logic) {
        super(owner, "Регистрация новой учётной записи", true);
        this.logic = logic;
        initComponents();
        _setLocation();
        _config();
    }

    public RegistrationWindow(JDialog owner, InnerLogic logic) {
        super(owner, "Регистрация новой учётной записи", true);
        this.logic = logic;
        initComponents();
        _setLocation();
        _config();
    }

    //---------------------Inner methoods--------------------------------
      private void _setLocation(){
        Toolkit tk = Toolkit.getDefaultToolkit();
        Dimension dm = tk.getScreenSize();
        int xPos = dm.width/2 - getWidth()/2;
        int yPos = dm.height/2 - getHeight()/2;
        setLocation(xPos,yPos);
       }

      private void _config(){
        jLabel2.setIcon(new ImageIcon("pict/login_16.png"));
        jLabel1.setIcon(new ImageIcon("pict/pwd_16.png"));
        butConnect.setIcon(new javax.swing.ImageIcon("pict/connect_16.png"));

        butConnect.addActionListener(new ActionListener(){
         public void actionPerformed(ActionEvent e) {
            wnd.setVisible(true);
           }
         });
        isAnotherComputer.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                if (isAnotherComputer.isSelected())
                    isSavePassword.setEnabled(false);
                else
                    isSavePassword.setEnabled(true);
            }
        });
      }

      private boolean _check(String str, String what){
      if(str == null || str.equals("")){
        StatusBar.setText("Ошибка: " + what + " пуст" );
        return false;
      }

      StringBuilder builder = new StringBuilder(str);
      boolean isFirstCharacter = true;
      for(int i = 0; i < builder.length(); i++){
        char currentChar = builder.charAt(i);
        if( !Character.isLetter(currentChar) && !Character.isDigit(currentChar) && (currentChar != '-') && (currentChar != '_') ){
          StatusBar.setText(what + " может состоять только из символов латинского языка, кириллицы,цифр, символов _ или -");
          return false;
        }

        if(isFirstCharacter){
          isFirstCharacter = false;
          if(Character.isDigit(currentChar) || (currentChar == '-') ){
           StatusBar.setText(what + " не может начиначаться с символа - или цифры");
           return false;
          }
        }
      }
      return true;
    }


    //-------------------------------------------------------------------
    // <editor-fold defaultstate="collapsed" desc="initComponents() - NetBeans code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        Password = new javax.swing.JPasswordField();
        Login = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        ConfirmPassword = new javax.swing.JPasswordField();
        jPanel2 = new javax.swing.JPanel();
        isAnotherComputer = new javax.swing.JCheckBox();
        isSavePassword = new javax.swing.JCheckBox();
        RegisterBtn = new javax.swing.JButton();
        CancelBtn = new javax.swing.JButton();
        butConnect = new javax.swing.JButton();
        StatusBar = new javax.swing.JTextArea();

        setTitle("Регистрация новой учётной записи");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setForeground(java.awt.Color.white);
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Регистрационные данные"));

        Password.setToolTipText("Поле для ввода пароля");
        Password.setName("Password"); // NOI18N

        Login.setToolTipText("Поле для ввода логина");

        jLabel1.setText("Пароль:");
        jLabel1.setToolTipText("Пароль - это секретное слово или набор символов, предназначенный для подтверждения личности или полномочий.");

        jLabel2.setText("Логин");
        jLabel2.setToolTipText("Логин - Имя учётной записи пользователя в любой форме.");

        jLabel3.setText("Подтвердите пароль:");
        jLabel3.setToolTipText("Пароль - это секретное слово или набор символов, предназначенный для подтверждения личности или полномочий.");

        ConfirmPassword.setToolTipText("Поле для повторного ввода пароля");
        ConfirmPassword.setName("Password"); // NOI18N
        //butConnect.setIcon(new ImageIcon("pict/ntwrk_24.gif")); // NOI18N
        butConnect.setToolTipText("Если у вас проблемы с подключением, то вы можете просмотреть и при необходимости изменить настройки подключения");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(5, 5, 5)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(Password, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 355, Short.MAX_VALUE)
                    .addComponent(ConfirmPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 355, Short.MAX_VALUE)
                    .addComponent(Login, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 355, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(Login, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(Password, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(ConfirmPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Дополнительные параметры"));

        isAnotherComputer.setText("Чужой компьютер");
        isAnotherComputer.setToolTipText("Режим \"Чужой компьютер\" - режм при котором информация о ваших персональных данных не будет сохранена или в каком то виде зафиксирована при работа на данном компьютере");
        isSavePassword.setText("Сохранить пароль на этом компьютере");
        isSavePassword.setToolTipText("Позволить системе сохранить ваш персональный пароль на данном компьютере. При повторной авторизации пароль будет введён автоматически.");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(isAnotherComputer, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE)
                    .addComponent(isSavePassword, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 480, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(isAnotherComputer)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(isSavePassword)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        RegisterBtn.setText("Зарегистрировать новую учётную запись");
        RegisterBtn.setToolTipText("Нажмите, если уверены, что хотите попробовать зарегистрировать введённые учётные данные.");
        RegisterBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RegisterBtnActionPerformed(evt);
            }
        });

        CancelBtn.setText("Отмена");
        CancelBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                CancelBtnActionPerformed(evt);
            }
        });

        StatusBar.setEditable(false);
        StatusBar.setWrapStyleWord(true);
        StatusBar.setAutoscrolls(true);
        StatusBar.setBackground(new Color(229,189,0));
        StatusBar.setText("Введите регистрационные данные...");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(butConnect, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(RegisterBtn, javax.swing.GroupLayout.DEFAULT_SIZE, 423, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(CancelBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
            .addComponent(StatusBar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 524, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(butConnect)
                    .addComponent(CancelBtn)
                    .addComponent(RegisterBtn)
                    )
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(StatusBar, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>

    private void CancelBtnActionPerformed(java.awt.event.ActionEvent evt) {
        isResult = false;
        setVisible(false);
    }

    private void RegisterBtnActionPerformed(java.awt.event.ActionEvent evt)  {
       login = Login.getText();
       if(_check(login, "Логин")){}
       else return;

       password = new String(Password.getPassword());
       if(_check(password, "Пароль")){}
       else return;

       if(password.length() < MIN_LEN_PASSWORD){
         StatusBar.setText("Пароль не может быть меньше чем " +  MIN_LEN_PASSWORD + " символов");
         return;
       }

       String repassword = new String(ConfirmPassword.getPassword());
       if(!password.equals(repassword)){
         StatusBar.setText("Пароли в полях ввода \"Пароль\" и \"Повторите пароль\" должны совпадать");
         return;
       }


       //------------Вот с этого момента начинается работа в сети--------------
       IAutorizationClient  autorizClient;
       long key=-1;

       try{
           autorizClient = (IAutorizationClient)logic.connectServer(wnd.getAddress());
           key=autorizClient.tryRegistration(login, password);
       }catch(RegistrationFailed e){
           StatusBar.setText("Регистрация завершилась неудачей" );
           return;
       }catch(Exception e){
           StatusBar.setText("Ошибка соединения" );
           return;
       }

       if(key==-1){StatusBar.setText("Сервер умер"); return; }
       //----------------------------------------------------------------------


       IsAnotherComputer = isAnotherComputer.isSelected();
       IsSavePassword = isSavePassword.isSelected();

       isResult = true;
       setVisible(false);
    }

    //-----------Class get-methood-----------------------------------------
    public boolean getResult(){
     return isResult;
    }

    public String getLogin(){
     return login;
    }

    public String getPassword(){
     return password;
    }

    public boolean getIsAnotherComputer(){
     return IsAnotherComputer;
    }

    public boolean getIsSavePassword(){
     return IsSavePassword;
    }

    public String getInetAddress(){
     return wnd.getAddress();
    }
    //---------------------------------------------------------------------
    // Variables declaration - do not modify
    private javax.swing.JButton CancelBtn;
    private javax.swing.JButton butConnect;
    private javax.swing.JPasswordField ConfirmPassword;
    private javax.swing.JTextField Login;
    private javax.swing.JPasswordField Password;
    private javax.swing.JButton RegisterBtn;
    private javax.swing.JTextArea StatusBar;
    private javax.swing.JCheckBox isAnotherComputer;
    private javax.swing.JCheckBox isSavePassword;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    // End of variables declaration

}
